import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'note.dart';
import 'folder.dart';
import '../services/storage_service.dart';

/**
 * 应用全局状态管理
 * 使用 ChangeNotifier 实现状态管理
 */
class AppState extends ChangeNotifier {
  // 当前选中的文件夹
  String _currentFolderId = '1'; // 默认选中"全部笔记"
  
  // 当前选中的笔记
  Note? _currentNote;
  
  // 文件夹列表
  List<Folder> _folders = [
    Folder.allNotes,
    Folder.uncategorized,
  ];
  
  // 笔记列表
  List<Note> _notes = [];
  
  // 搜索关键词
  String _searchQuery = '';
  
  // 是否显示设置面板
  bool _showSettings = false;
  
  // 主题和外观设置
  ThemeMode _themeMode = ThemeMode.system;
  Color? _primaryColor;
  double _fontScale = 1.0;
  
  // 布局设置
  bool _autoAdaptLayout = true;
  bool _compactMode = false;
  
  // 高级设置
  bool _enableAnimations = true;
  bool _performanceMode = false;

  // Getters
  String get currentFolderId => _currentFolderId;
  Note? get currentNote => _currentNote;
  List<Folder> get folders => List.unmodifiable(_folders);
  List<Note> get notes => List.unmodifiable(_notes);
  String get searchQuery => _searchQuery;
  bool get showSettings => _showSettings;
  
  // 主题和外观设置 Getters
  ThemeMode get themeMode => _themeMode;
  Color? get primaryColor => _primaryColor;
  double get fontScale => _fontScale;
  
  // 布局设置 Getters
  bool get autoAdaptLayout => _autoAdaptLayout;
  bool get compactMode => _compactMode;
  
  // 高级设置 Getters
  bool get enableAnimations => _enableAnimations;
  bool get performanceMode => _performanceMode;

  /**
   * 获取当前文件夹
   */
  Folder? get currentFolder {
    return _folders.firstWhere(
      (folder) => folder.id.toString() == _currentFolderId,
      orElse: () => Folder.allNotes,
    );
  }

  /**
   * 获取过滤后的笔记列表
   */
  List<Note> get filteredNotes {
    List<Note> filtered = _notes;

    // 按文件夹过滤
    if (_currentFolderId != '1') { // 不是"全部笔记"
      filtered = filtered.where((note) => 
        note.folderId.toString() == _currentFolderId).toList();
    }

    // 按搜索关键词过滤
    if (_searchQuery.isNotEmpty) {
      filtered = filtered.where((note) =>
        note.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
        note.content.toLowerCase().contains(_searchQuery.toLowerCase())).toList();
    }

    // 按更新时间倒序排列
    filtered.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));

    return filtered;
  }

  /**
   * 选择文件夹
   */
  void selectFolder(String folderId) {
    if (_currentFolderId != folderId) {
      _currentFolderId = folderId;
      _currentNote = null; // 切换文件夹时清空当前笔记
      notifyListeners();
    }
  }

  /**
   * 选择笔记
   */
  void selectNote(Note? note) {
    if (_currentNote != note) {
      _currentNote = note;
      notifyListeners();
    }
  }

  /**
   * 设置搜索关键词
   */
  void setSearchQuery(String query) {
    if (_searchQuery != query) {
      _searchQuery = query;
      notifyListeners();
    }
  }

  /**
   * 显示/隐藏设置面板
   */
  void toggleSettings() {
    _showSettings = !_showSettings;
    notifyListeners();
  }

  /**
   * 创建新笔记
   */
  Future<void> createNote() async {
    try {
      final folderId = _currentFolderId == '1' ? 2 : int.parse(_currentFolderId); // 默认为未分类笔记
      final note = Note(
        id: 0,
        title: '',
        content: '',
        folderId: folderId,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      );
      
      final savedNote = await StorageService.saveNote(note);
      _notes.insert(0, savedNote);
      _updateFolderCounts();
      selectNote(savedNote);
      notifyListeners();
    } catch (e) {
      print('创建笔记失败: $e');
    }
  }

  /**
   * 添加笔记
   */
  void addNote(Note note) {
    _notes.insert(0, note); // 插入到列表开头
    _currentNote = note;
    _updateFolderCounts();
    notifyListeners();
  }

  /**
   * 更新笔记
   */
  Future<void> updateNote(Note updatedNote) async {
    try {
      final savedNote = await StorageService.saveNote(updatedNote);
      final index = _notes.indexWhere((note) => note.id == updatedNote.id);
      if (index != -1) {
        _notes[index] = savedNote;
        if (_currentNote?.id == updatedNote.id) {
          _currentNote = savedNote;
        }
        _updateFolderCounts();
        notifyListeners();
      }
    } catch (e) {
      print('更新笔记失败: $e');
    }
  }

  /**
   * 删除笔记
   */
  Future<void> deleteNote(int noteId) async {
    try {
      await StorageService.deleteNote(noteId);
      _notes.removeWhere((note) => note.id == noteId);
      
      if (_currentNote?.id == noteId) {
        _currentNote = null;
      }
      
      _updateFolderCounts();
      notifyListeners();
    } catch (e) {
      print('删除笔记失败: $e');
    }
  }

  /**
   * 创建文件夹
   */
  Future<void> createFolder(String name) async {
    try {
      final folder = Folder(
        id: 0,
        name: name,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      );
      
      final savedFolder = await StorageService.saveFolder(folder);
      _folders.add(savedFolder);
      notifyListeners();
    } catch (e) {
      print('创建文件夹失败: $e');
    }
  }

  /**
   * 添加文件夹
   */
  void addFolder(Folder folder) {
    _folders.add(folder);
    notifyListeners();
  }

  /**
   * 更新文件夹
   */
  Future<void> updateFolder(Folder updatedFolder) async {
    try {
      final savedFolder = await StorageService.saveFolder(updatedFolder);
      final index = _folders.indexWhere((folder) => folder.id == updatedFolder.id);
      if (index != -1) {
        _folders[index] = savedFolder;
        notifyListeners();
      }
    } catch (e) {
      print('更新文件夹失败: $e');
    }
  }

  /**
   * 删除文件夹
   */
  Future<void> deleteFolder(int folderId) async {
    try {
      await StorageService.deleteFolder(folderId);
      _folders.removeWhere((folder) => folder.id == folderId);
      
      // 将该文件夹下的笔记移动到未分类笔记
      for (int i = 0; i < _notes.length; i++) {
        if (_notes[i].folderId == folderId) {
          final updatedNote = _notes[i].copyWith(folderId: 2);
          await StorageService.saveNote(updatedNote);
          _notes[i] = updatedNote;
        }
      }
      
      // 如果删除的是当前选中的文件夹，切换到全部笔记
      if (_currentFolderId == folderId.toString()) {
        selectFolder('1');
      }
      
      _updateFolderCounts();
      notifyListeners();
    } catch (e) {
      print('删除文件夹失败: $e');
    }
  }

  /**
   * 移动笔记到指定文件夹
   */
  void moveNoteToFolder(int noteId, int targetFolderId) {
    final index = _notes.indexWhere((note) => note.id == noteId);
    if (index != -1) {
      _notes[index] = _notes[index].copyWith(
        folderId: targetFolderId,
        updatedAt: DateTime.now(),
      );
      _updateFolderCounts();
      notifyListeners();
    }
  }

  /**
   * 设置笔记列表
   */
  void setNotes(List<Note> notes) {
    _notes = List.from(notes);
    _updateFolderCounts();
    notifyListeners();
  }

  /**
   * 设置文件夹列表
   */
  void setFolders(List<Folder> folders) {
    _folders = List.from(folders);
    notifyListeners();
  }

  /**
   * 更新文件夹笔记数量
   */
  void _updateFolderCounts() {
    for (int i = 0; i < _folders.length; i++) {
      final folder = _folders[i];
      int count;
      
      if (folder.id == 1) {
        // "全部笔记"显示所有笔记数量
        count = _notes.length;
      } else {
        // 其他文件夹显示对应的笔记数量
        count = _notes.where((note) => note.folderId == folder.id).length;
      }
      
      _folders[i] = folder.copyWith(count: count);
    }
  }

  /**
   * 初始化应用状态
   */
  Future<void> initialize() async {
    await _loadFolders();
    await _loadNotes();
    
    // 默认选择第一个文件夹
    if (_folders.isNotEmpty) {
      selectFolder(_folders.first.id.toString());
    }
  }

  /**
   * 加载文件夹列表
   */
  Future<void> _loadFolders() async {
    try {
      _folders = await StorageService.getAllFolders();
      notifyListeners();
    } catch (e) {
      print('加载文件夹失败: $e');
    }
  }

  /**
   * 加载笔记列表
   */
  Future<void> _loadNotes() async {
    try {
      _notes = await StorageService.getAllNotes();
      _updateFolderCounts();
      notifyListeners();
    } catch (e) {
      print('加载笔记失败: $e');
    }
  }

  /**
   * 切换设置面板显示状态
   */
  void toggleSettingsPanel() {
    _showSettings = !_showSettings;
    notifyListeners();
  }

  // 主题和外观设置方法
  
  /**
   * 设置主题模式
   */
  void setThemeMode(ThemeMode mode) {
    if (_themeMode != mode) {
      _themeMode = mode;
      notifyListeners();
    }
  }

  /**
   * 设置主色调
   */
  void setPrimaryColor(Color? color) {
    if (_primaryColor != color) {
      _primaryColor = color;
      notifyListeners();
    }
  }

  /**
   * 设置字体缩放比例
   */
  void setFontScale(double scale) {
    if (_fontScale != scale) {
      _fontScale = scale;
      notifyListeners();
    }
  }

  // 布局设置方法
  
  /**
   * 设置自动适配布局
   */
  void setAutoAdaptLayout(bool enabled) {
    if (_autoAdaptLayout != enabled) {
      _autoAdaptLayout = enabled;
      notifyListeners();
    }
  }

  /**
   * 设置紧凑模式
   */
  void setCompactMode(bool enabled) {
    if (_compactMode != enabled) {
      _compactMode = enabled;
      notifyListeners();
    }
  }

  // 高级设置方法
  
  /**
   * 设置动画效果
   */
  void setEnableAnimations(bool enabled) {
    if (_enableAnimations != enabled) {
      _enableAnimations = enabled;
      notifyListeners();
    }
  }

  /**
   * 设置性能模式
   */
  void setPerformanceMode(bool enabled) {
    if (_performanceMode != enabled) {
      _performanceMode = enabled;
      notifyListeners();
    }
  }

  /**
   * 重置所有设置为默认值
   */
  void resetSettings() {
    _themeMode = ThemeMode.system;
    _primaryColor = null;
    _fontScale = 1.0;
    _autoAdaptLayout = true;
    _compactMode = false;
    _enableAnimations = true;
    _performanceMode = false;
    notifyListeners();
  }

  /**
   * 清空所有数据
   */
  void clearAll() {
    _notes.clear();
    _folders = [Folder.allNotes, Folder.uncategorized];
    _currentNote = null;
    _currentFolderId = '1';
    _searchQuery = '';
    _showSettings = false;
    // 重置设置
    resetSettings();
    notifyListeners();
  }
}